import DexieCtx from '@/utils/dexiectx';
import GramClient from "@/utils/gramclient";

class TabizooTgweb {
  constructor() {
  }
  async allRun() {
    this.dexie = await DexieCtx.db()
    const allAccounts = await this.dexie.accounts.where("session").notEqual("").toArray()

    let sepIndex = 0;
    const groupStep = 5
    while (true) {
      if (sepIndex >= allAccounts.length) {
        break;
      }
      const start = sepIndex
      const end = Math.min(sepIndex + groupStep, allAccounts.length)
      const accountsGroup = allAccounts.slice(start, end)
      try {
        const promiseGroup = accountsGroup.map(async account => {
          const gameInfo = await this.dexie.tabizoo.get({ phone: account.phone })
          return this.run(account, gameInfo)
        })
        await Promise.allSettled(promiseGroup)
        console.log(Date() + "Tabizoo tgweb finished " + start + "~" + end)
      } catch (error) {
        console.error(error)
      } finally {
        sepIndex = end
      }
    }
  }

  async run(account, gameInfo) {
    try {
      gameInfo = gameInfo ?? {}
      const client = new GramClient(account)
      await client.open()
      if (gameInfo.isJoinChannel != true) {
        const isJoined = await client.joinChannel("tabi_ann")
        gameInfo.isJoinChannel = isJoined
      }
      const gameUrl = "https://t.me/tabizoobot/tabizoo";
      const bot = "tabizoobot";
      const url = await client.getTgwebUrl(bot, gameUrl);
      console.log(account.phone, url);
      await client.close()
      await this.updateTabizooTable(account.phone, url, gameInfo.isJoinChannel)
    } catch (error) {
      console.error(account.phone, error)
    }
  }

  async updateTabizooTable(phone, tgweb, isJoinChannel) {
    const oldValue = await this.dexie.tabizoo.get({
      phone: phone
    })
    const dateStr = (new Date()).toLocaleString()
    if (oldValue == null) {
      await this.dexie.tabizoo.add({
        phone,
        tgweb: tgweb,
        tokenupdate: dateStr,
        isJoinChannel: isJoinChannel,
      })
    } else {
      await this.dexie.tabizoo.where("phone").equals(phone).modify({
        tgweb: tgweb,
        tokenupdate: dateStr,
        isJoinChannel: isJoinChannel,
      })
    }
  }
}

export default TabizooTgweb